﻿import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Post } from '../models/post';

/*
  Generated class for the Post provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class PostService {

    private postsUrl: string = 'http://www.dungang.site/api/articles';
    private postUrl: string = 'http://www.dungang.site/api/article';
    
    constructor(public http: Http) {
        console.log('Hello Post Provider');
    }

    /**
     * 获取文章列表
     */
    getPosts(): Promise<Post[]> {
        return this.http.get(this.postsUrl)
            .toPromise()
            .then(response => response.json().posts as Post[])
            .catch(this.handleError);
    }

    /**
     * 获取文章详情
     * @param id
     */
    getPost(id: number): Promise<Post> {
        return this.http.get(this.postUrl+'?id='+id)
            .toPromise()
            .then(response => response.json().post as Post)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred');
        return Promise.reject(error.message || error);
    }
}
